package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//过滤器
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    //路径匹配器  支持通配符
    public static  final AntPathMatcher PA = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;

        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1 获取用户请求的URL路径
        String requestURI = request.getRequestURI();

        log.info("拦截到请求: {}",requestURI);

        //2 定义无需处理的请求路径
        String[] urls = new String[]{
                "/employee/login",  // 网页端登录
                "/employee/logout", // 网页端退出
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg", // 移动端发送短信
                "/user/login",// 移动端登录
                "/doc.html",// 1 将Swagger及Knife4j的相关静态资源直接放行,无需登录即可访问
                "/webjars/**",//2
                "/swagger-resources",//3
                "/v2/api-docs" //4
        };

        //3 判断当前请求是否需要处理
        boolean check = check(urls , requestURI);

        //4 若无需处理,则直接放行
        if (check){
            log.info("此次请求{}无需处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        //5.1 对网页端的登录状态进行判断 已经登录就直接放行
        if (request.getSession().getAttribute("employee") != null){
            log.info("用户已登陆,当前用户的id为: {}",request.getSession().getAttribute("employee"));
            /*//对当前经过的线程进行打印
            long id = Thread.currentThread().getId();
            log.info("线程id为：{}",id);*/

            Long employee = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(employee);

            filterChain.doFilter(request,response);
            return;
        }

        //5.2 判断移动端的登录状态，如果已登录，则直接放行
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long user = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(user);

            filterChain.doFilter(request,response);
            return;
        }

        log.info("当前用户未登录");

        //6 若未登录就返回未登录结果,通过输出流的方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    // 判断当前请求是否需要进行处理
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PA.match(url, requestURI);
            if (match){
                return true;
            }
        }
        return false;
    }
}
